package cn.netjava.dao;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import cn.netjava.dbutil.Conn2DB;
import cn.netjava.pojo.ReplayReview;

/**
 * this class is use for dealing with review's replay
 * @author Administrator
 *
 */
public class ReplayReviewDao {
	public static ReplayReviewDao rrdao=null;
	
	/*make ReplayReviewDao pravate*/
	private ReplayReviewDao(){}
	
	/*obtain a ReplayReviewDao object*/
	public static ReplayReviewDao getReplayReviewDao(){
		if(null==rrdao){
			rrdao =new ReplayReviewDao();
		}
		return rrdao;
	}
	
	/**
	 * this method is use for adding a review's replay to mysql
	 * @param ReplayReviewContent
	 * @param userID
	 * @param reviewID
	 * @return
	 */
	public boolean addReplayReview(String ReplayReviewContent,int userID,int reviewID){
		String sql = "insert into tbl_replayreviews(replayreviewcontent,ins_uid,ins_reviewid,ins_dt)values(?,?,?,?)";
		try{
			java.sql.Connection conn =Conn2DB.getConn();
			java.sql.PreparedStatement pstmt =conn.prepareStatement(sql);
			
			pstmt.setString(1, ReplayReviewContent);
			pstmt.setInt(2, userID);
			pstmt.setInt(3, reviewID);
			/*obtain the system time*/
			java.sql.Timestamp timeStamp =new java.sql.Timestamp(System.currentTimeMillis());
			String ins_td =timeStamp.toString().substring(0,timeStamp.toString().lastIndexOf("."));
			pstmt.setString(4, ins_td);   
			
            pstmt.executeUpdate();
			
			pstmt.close();
			return true;
		}catch(Exception ef){
			ef.printStackTrace();
		}
		return false;
	}
	
	/**
	 * to get review's replay List according to review id
	 * @param reviewID
	 * @return
	 */
	public List<ReplayReview> getReplayReviewFromReviewID(int reviewID){
		List<ReplayReview> replayReviewList =new ArrayList<ReplayReview>();
		String sql="select * from tbl_replayreviews where ins_reviewid=?";
		try{
			java.sql.Connection conn =Conn2DB.getConn();
			java.sql.PreparedStatement pstmt =conn.prepareStatement(sql);
			
			pstmt.setInt(1, reviewID);
			ResultSet rs = pstmt.executeQuery();
			while(rs.next()){
				ReplayReview replayReview =new ReplayReview();
				replayReview.setId(rs.getInt("id"));
				replayReview.setReplayReviewContent(rs.getString("replayreviewcontent"));
				
				ReviewDao rdao =ReviewDao.getReviewDao();
				replayReview.setReview(rdao.getReviewFromReviewID(rs.getInt("ins_reviewid")));
			
				UserDao udao =UserDao.getUserDao();
				replayReview.setUser(udao.getUserFromID(rs.getInt("ins_uid")));
				
				replayReview.setIns_dt(rs.getString("ins_dt"));
			}
			pstmt.close();
			rs.close();
		}catch(Exception ef){
			ef.printStackTrace();
		}
		return replayReviewList;
	}

}
